package kernel

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var (
	DB *sql.DB
)

func NewMySQL(config *MySQL) (db *sql.DB, err error) {
	db, err = sql.Open("mysql", config.GetDSN())
	if err != nil {
		return
	}
	db.SetMaxOpenConns(config.MaxOpenConns)
	db.SetMaxIdleConns(config.MaxIdleConns)

	// 验证数据库连接
	if err = db.Ping(); err != nil {
		db.Close()
		return nil, err
	}

	return
}

type MySQL struct {
	Host                      string `mapstructure:"host" json:"host"`
	Port                      int    `mapstructure:"port" json:"port"`
	User                      string `mapstructure:"user" json:"user"`
	Pass                      string `mapstructure:"pass" json:"pass"`
	Name                      string `mapstructure:"name" json:"name"`
	Charset                   string `mapstructure:"charset" json:"charset"`
	MaxOpenConns              int    `mapstructure:"max-open-conns" json:"max-open-conns"`
	MaxIdleConns              int    `mapstructure:"max-idle-conns" json:"max-idle-conns"`
	SkipInitializeWithVersion bool   `mapstructure:"skip-initialize-with-version" json:"skip-initialize-with-version"`
	DefaultStringSize         uint   `mapstructure:"default-string-size" json:"default-string-size"`
}

func (conf *MySQL) GetDSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", conf.User, conf.Pass, conf.Host, conf.Port, conf.Name, conf.Charset)
}
